package realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import org.apache.doris.flink.sink.DorisSink;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.*;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import realtime.beans.UserReviewBean;
import realtime.util.DateFormatUtil;
import realtime.util.DorisUtil;
import realtime.util.EnvUtil;
import realtime.util.KafkaUtil;

import java.time.Duration;

/**
 * @Create 2023/9/9 8:35
 * 课程评价情况
 */
public class DwsTradeCouCommentInfo {
    public static void main(String[] args) {

        //TODO 1、设置环境
        StreamExecutionEnvironment env = EnvUtil.getSEE(4);

        DataStreamSource<String> sourceDS = env.fromSource(KafkaUtil.getKafkaConsumer("dwd_interaction_course_review", "dws_CCI"),
                WatermarkStrategy.noWatermarks(), "dwd_interaction_course_review"
        );

        //TODO 2、etl
        SingleOutputStreamOperator<JSONObject> JsonObjDS = sourceDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    out.collect(jsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ZERO)
                .withTimestampAssigner((value,ts)->value.getLong("ts")*1000));

        //TODO 3、按user聚合，添加用户分数，用户数,好评数并转换为包装类
        SingleOutputStreamOperator<UserReviewBean> processDS = JsonObjDS.keyBy(value -> value.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, UserReviewBean>() {

                    ValueState<String> valueState;
                    MapState<String,String> mapState;

                    @Override
                    public void open(Configuration parameters) throws Exception {

                        StateTtlConfig ttlConfig = StateTtlConfig.newBuilder(Time.days(1))
                                .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build();

                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("state", String.class);
                        valueStateDescriptor.enableTimeToLive(ttlConfig);


                        valueState = getRuntimeContext().getState(valueStateDescriptor);

                        mapState= getRuntimeContext().getMapState(new MapStateDescriptor<String, String>("mapstate", String.class, String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, UserReviewBean>.Context ctx, Collector<UserReviewBean> out) throws Exception {

                        UserReviewBean userReviewBean = new UserReviewBean();
                        Long reviewStars = value.getLong("review_stars");
                        String courseId = value.getString("course_id");
                        userReviewBean.setStars(reviewStars);
                        userReviewBean.setCourseId(courseId);
                        userReviewBean.setUserCt(1L);


                        if (reviewStars >= 5) {
                            userReviewBean.setGoodCt(1L);
                            //mapState.put(courseId,"1");
                        } else {
                            userReviewBean.setGoodCt(0L);
                        }

                        /*if (mapState.get(courseId) == null) {
                            mapState.put(courseId,"1");
                            userReviewBean.setUserCt(1L);
                        } else {
                            userReviewBean.setUserCt(0L);
                        }*/

                        out.collect(userReviewBean);

                    }
                });

        //TODO 4、按课程聚合,聚合统计
        SingleOutputStreamOperator<UserReviewBean> reduceDS = processDS.keyBy(value -> value.getCourseId())
                .window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(5)))
                .reduce(new ReduceFunction<UserReviewBean>() {
                    @Override
                    public UserReviewBean reduce(UserReviewBean value1, UserReviewBean value2) throws Exception {
                        value1.setStars(value1.getStars() + value2.getStars());
                        value1.setGoodCt(value1.getGoodCt() + value2.getGoodCt());
                        value1.setUserCt(value1.getUserCt() + value2.getUserCt());
                        return value1;
                    }
                }, new WindowFunction<UserReviewBean, UserReviewBean, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<UserReviewBean> input, Collector<UserReviewBean> out) throws Exception {
                        UserReviewBean reviewBean = input.iterator().next();

                        long start = window.getStart();
                        long end = window.getEnd();


                        long timeMillis = System.currentTimeMillis();
                        reviewBean.setStt(DateFormatUtil.toYmdHms(start));
                        reviewBean.setEdt(DateFormatUtil.toYmdHms(end));
                        reviewBean.setCurDate(DateFormatUtil.toDate(timeMillis));

                        out.collect(reviewBean);
                    }
                });

        SingleOutputStreamOperator<String> endDS= reduceDS.map(value -> {
            SerializeConfig serializeConfig = new SerializeConfig();
            serializeConfig.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
            String jsonString = JSONObject.toJSONString(value, serializeConfig);
            return jsonString;
        });

        //endDS.print();
        //TODO 14、数据写入doris中
        DorisSink<String> dorisSink = DorisUtil.getDorisSink("dws_course_comment_info_window");

        endDS.sinkTo(dorisSink);

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
}
